<template>
  <div class="cards-container">
    <h1>知识卡片库</h1>
    
    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-group">
        <label for="document-filter">文档:</label>
        <select id="document-filter" v-model="documentFilter" class="filter-select">
          <option value="">全部文档</option>
          <option v-for="doc in documents" :key="doc._id" :value="doc._id">
            {{ doc.title || doc.filename }}
          </option>
        </select>
      </div>
      
      <div class="filter-group">
        <label for="difficulty-filter">难度:</label>
        <select id="difficulty-filter" v-model="difficultyFilter" class="filter-select">
          <option value="">全部难度</option>
          <option value="EASY">简单</option>
          <option value="MEDIUM">中等</option>
          <option value="HARD">困难</option>
        </select>
      </div>
      
      <div class="filter-group">
        <label for="tag-filter">标签:</label>
        <select id="tag-filter" v-model="tagFilter" class="filter-select">
          <option value="">全部标签</option>
          <option v-for="tag in tags" :key="tag" :value="tag">{{ tag }}</option>
        </select>
      </div>
      
      <div class="filter-group search-group">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索卡片..." 
          class="search-input"
        />
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <p>加载中...</p>
    </div>
    
    <!-- 错误信息 -->
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
    
    <!-- 空状态 -->
    <div v-if="!loading && !filteredCards.length" class="empty-state">
      <p>没有找到符合条件的知识卡片</p>
    </div>
    
    <!-- 卡片列表 -->
    <div v-if="!loading && filteredCards.length" class="card-grid">
      <div 
        v-for="card in filteredCards" 
        :key="card._id" 
        class="card-item"
        :class="{ 'card-bookmarked': isBookmarked(card._id) }"
      >
        <div class="card-header">
          <div class="card-meta">
            <span :class="['difficulty', getDifficultyClass(card.difficulty)]">
              {{ getDifficultyText(card.difficulty) }}
            </span>
            
            <span v-if="card.documentTitle" class="document-name" :title="card.documentTitle">
              {{ card.documentTitle }}
            </span>
          </div>
          
          <button 
            @click="toggleBookmark(card._id)" 
            class="btn-bookmark"
            :title="isBookmarked(card._id) ? '取消收藏' : '收藏'"
          >
            <span v-if="isBookmarked(card._id)">★</span>
            <span v-else>☆</span>
          </button>
        </div>
        
        <div class="card-content">
          <h3>{{ card.title }}</h3>
          <p>{{ card.content }}</p>
          
          <div v-if="card.tags && card.tags.length" class="card-tags">
            <span v-for="tag in card.tags" :key="tag" class="tag">
              {{ tag }}
            </span>
          </div>
        </div>
        
        <div class="card-footer">
          <router-link :to="`/cards/${card._id}`" class="btn-view-card">
            查看详情
          </router-link>
          
          <button @click="generateExercise(card._id)" class="btn-generate-exercise">
            生成练习
          </button>
        </div>
      </div>
    </div>
    
    <!-- 分页控件 -->
    <div v-if="totalPages > 1" class="pagination">
      <button 
        @click="changePage(currentPage - 1)" 
        :disabled="currentPage === 1"
        class="btn-page"
      >
        上一页
      </button>
      
      <span class="page-info">{{ currentPage }} / {{ totalPages }}</span>
      
      <button 
        @click="changePage(currentPage + 1)" 
        :disabled="currentPage === totalPages"
        class="btn-page"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useUserStore } from '@/store/user';
import { cardApi, documentApi, exerciseApi } from '@/services/api';

const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 状态变量
const loading = ref(false);
const error = ref('');
const cards = ref([]);
const documents = ref([]);
const tags = ref([]);
const documentFilter = ref('');
const difficultyFilter = ref('');
const tagFilter = ref('');
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(12);
const totalCards = ref(0);

// 从路由参数获取初始筛选条件
onMounted(async () => {
  if (route.query.document) {
    documentFilter.value = route.query.document;
  }
  
  if (route.query.difficulty) {
    difficultyFilter.value = route.query.difficulty;
  }
  
  if (route.query.tag) {
    tagFilter.value = route.query.tag;
  }
  
  if (route.query.search) {
    searchQuery.value = route.query.search;
  }
  
  if (route.query.page) {
    currentPage.value = parseInt(route.query.page) || 1;
  }
  
  // 获取文档列表和标签列表
  await Promise.all([
    fetchDocuments(),
    fetchAllTags()
  ]);
  
  // 获取卡片列表
  await fetchCards();
});

// 监听筛选条件变化
watch([documentFilter, difficultyFilter, tagFilter, searchQuery], () => {
  // 重置页码
  currentPage.value = 1;
  
  // 更新路由参数
  updateRouteQuery();
  
  // 重新获取卡片
  fetchCards();
});

// 监听页码变化
watch(currentPage, () => {
  // 更新路由参数
  updateRouteQuery();
  
  // 重新获取卡片
  fetchCards();
});

// 计算属性
const filteredCards = computed(() => cards.value);

const totalPages = computed(() => {
  return Math.ceil(totalCards.value / pageSize.value) || 1;
});

// 方法
const fetchCards = async () => {
  loading.value = true;
  error.value = '';
  
  try {
    // 构建查询参数
    const params = {
      page: currentPage.value,
      limit: pageSize.value
    };
    
    if (documentFilter.value) {
      params.documentId = documentFilter.value;
    }
    
    if (difficultyFilter.value) {
      params.difficulty = difficultyFilter.value;
    }
    
    if (tagFilter.value) {
      params.tag = tagFilter.value;
    }
    
    if (searchQuery.value) {
      params.search = searchQuery.value;
    }
    
    const response = await cardApi.getAll(params);
    cards.value = response.data.cards;
    totalCards.value = response.data.total;
  } catch (err) {
    error.value = '获取卡片失败';
    console.error('获取卡片失败:', err);
  } finally {
    loading.value = false;
  }
};

const fetchDocuments = async () => {
  try {
    const response = await documentApi.getAll();
    documents.value = response.data;
  } catch (err) {
    console.error('获取文档列表失败:', err);
  }
};

const fetchAllTags = async () => {
  try {
    const response = await cardApi.getAllTags();
    tags.value = response.data.map(item => item.tag);
  } catch (err) {
    console.error('获取标签列表失败:', err);
  }
};

const updateRouteQuery = () => {
  const query = {};
  
  if (documentFilter.value) {
    query.document = documentFilter.value;
  }
  
  if (difficultyFilter.value) {
    query.difficulty = difficultyFilter.value;
  }
  
  if (tagFilter.value) {
    query.tag = tagFilter.value;
  }
  
  if (searchQuery.value) {
    query.search = searchQuery.value;
  }
  
  if (currentPage.value > 1) {
    query.page = currentPage.value;
  }
  
  router.replace({ query });
};

const changePage = (page) => {
  if (page < 1 || page > totalPages.value) return;
  currentPage.value = page;
};

const isBookmarked = (cardId) => {
  const bookmarks = userStore.getBookmarks;
  return bookmarks.some(bookmark => bookmark.cardId === cardId);
};

const toggleBookmark = async (cardId) => {
  try {
    if (isBookmarked(cardId)) {
      await userStore.removeBookmark(cardId);
    } else {
      await userStore.addBookmark(cardId);
    }
  } catch (err) {
    console.error('操作书签失败:', err);
  }
};

const generateExercise = async (cardId) => {
  try {
    await exerciseApi.generate(cardId);
    router.push(`/cards/${cardId}`);
  } catch (err) {
    console.error('生成练习题失败:', err);
  }
};

const getDifficultyText = (difficulty) => {
  if (difficulty === undefined || difficulty === null) return '未知难度';
  
  // 处理数字类型的难度值
  if (typeof difficulty === 'number') {
    switch (difficulty) {
      case 1: return '非常简单';
      case 2: return '简单';
      case 3: return '中等';
      case 4: return '困难';
      case 5: return '非常困难';
      default: return `难度 ${difficulty}`;
    }
  }
  
  // 处理字符串类型的难度值（向后兼容）
  const difficultyMap = {
    'EASY': '简单',
    'MEDIUM': '中等',
    'HARD': '困难',
    '1': '非常简单',
    '2': '简单',
    '3': '中等',
    '4': '困难',
    '5': '非常困难'
  };
  
  return difficultyMap[difficulty] || difficulty;
};

const getDifficultyClass = (difficulty) => {
  if (difficulty === undefined || difficulty === null) return '';
  
  // 处理数字类型的难度值
  if (typeof difficulty === 'number') {
    switch (difficulty) {
      case 1: return 'easy';
      case 2: return 'easy';
      case 3: return 'medium';
      case 4: return 'hard';
      case 5: return 'hard';
      default: return '';
    }
  }
  
  // 处理字符串类型的难度值（向后兼容）
  const difficultyMap = {
    'EASY': 'easy',
    'MEDIUM': 'medium',
    'HARD': 'hard',
    '1': 'easy',
    '2': 'easy',
    '3': 'medium',
    '4': 'hard',
    '5': 'hard'
  };
  
  return difficultyMap[difficulty] || '';
};
</script>

<style scoped>
.cards-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 2rem;
}

h1 {
  margin-bottom: 2rem;
  color: #333;
}

/* 筛选区域样式 */
.filter-section {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
  margin-bottom: 2rem;
  padding: 1.5rem;
  background-color: #f9f9f9;
  border-radius: 8px;
}

.filter-group {
  display: flex;
  flex-direction: column;
  min-width: 150px;
}

.search-group {
  flex-grow: 1;
}

.filter-group label {
  margin-bottom: 0.5rem;
  font-weight: 500;
  color: #555;
}

.filter-select, .search-input {
  padding: 0.75rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 0.9rem;
}

.filter-select:focus, .search-input:focus {
  outline: none;
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

/* 加载和错误状态样式 */
.loading-container, .empty-state {
  text-align: center;
  padding: 3rem;
  background-color: #f9f9f9;
  border-radius: 8px;
  color: #666;
}

.error-message {
  color: #ff3860;
  background-color: #feecf0;
  padding: 1rem;
  border-radius: 4px;
  margin-bottom: 1rem;
}

/* 卡片网格样式 */
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 1.5rem;
  margin-bottom: 2rem;
}

.card-item {
  border: 1px solid #eee;
  border-radius: 8px;
  padding: 1.5rem;
  background-color: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.card-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-item.card-bookmarked {
  border-color: #FFD700;
  box-shadow: 0 2px 8px rgba(255, 215, 0, 0.2);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 1rem;
}

.card-meta {
  display: flex;
  flex-direction: column;
  gap: 0.5rem;
}

.difficulty {
  padding: 0.25rem 0.5rem;
  border-radius: 12px;
  font-size: 0.75rem;
  font-weight: 500;
  display: inline-block;
}

.difficulty.easy {
  background-color: #e8f5e9;
  color: #2e7d32;
}

.difficulty.medium {
  background-color: #fff8e1;
  color: #ff8f00;
}

.difficulty.hard {
  background-color: #ffebee;
  color: #c62828;
}

.document-name {
  font-size: 0.8rem;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
}

.btn-bookmark {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  color: #FFD700;
}

.card-content {
  flex: 1;
}

.card-content h3 {
  margin-top: 0;
  margin-bottom: 0.5rem;
  color: #333;
  font-size: 1.1rem;
}

.card-content p {
  color: #555;
  margin-bottom: 1rem;
  font-size: 0.9rem;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.card-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
  margin-top: 0.5rem;
}

.tag {
  padding: 0.25rem 0.5rem;
  background-color: #f0f0f0;
  border-radius: 12px;
  font-size: 0.75rem;
  color: #666;
}

.card-footer {
  display: flex;
  gap: 0.75rem;
  margin-top: 1rem;
}

.btn-view-card, .btn-generate-exercise {
  padding: 0.5rem;
  border-radius: 4px;
  font-size: 0.9rem;
  cursor: pointer;
  text-align: center;
  flex: 1;
}

.btn-view-card {
  background-color: #2196F3;
  color: white;
  text-decoration: none;
  border: none;
}

.btn-view-card:hover {
  background-color: #1976D2;
}

.btn-generate-exercise {
  background-color: #FF9800;
  color: white;
  border: none;
}

.btn-generate-exercise:hover {
  background-color: #F57C00;
}

/* 分页控件样式 */
.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 1rem;
  margin-top: 2rem;
}

.btn-page {
  padding: 0.5rem 1rem;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  cursor: pointer;
}

.btn-page:hover:not(:disabled) {
  background-color: #f0f0f0;
}

.btn-page:disabled {
  color: #999;
  cursor: not-allowed;
}

.page-info {
  color: #666;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .filter-section {
    flex-direction: column;
    gap: 1rem;
  }
  
  .filter-group {
    width: 100%;
  }
}
</style> 